package com.mooc;

import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

public class AgentMainClass {
    public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException, ClassNotFoundException {
        System.out.println("最初返回值" + RandomUtil.create());
        String path = "E:\\project\\demo\\agent\\doc\\RandomUtil.class";
        byte[] bytes = ByteArrayUtil.getBytes(path);
        ClassDefinition classDefinition = new ClassDefinition(RandomUtil.class, bytes);
        inst.redefineClasses(classDefinition);

        System.out.println("修改后返回值" + RandomUtil.create());
        String rollBackPath = "E:\\project\\demo\\agent\\doc\\RandomUtilRollBack.class";
        byte[] rollBackBytes = ByteArrayUtil.getBytes(rollBackPath);
        ClassDefinition rollBackClassDefinition = new ClassDefinition(RandomUtil.class, rollBackBytes);
        inst.redefineClasses(rollBackClassDefinition);
        System.out.println("回滚后返回值" + RandomUtil.create());
    }
}
